import type { UnwrapRef } from 'vue'
import { ref } from "vue"

export function useAsync<T>(asyncFn: () => Promise<T>, initVal: T, immediate = true) {
    const pending = ref(false)
    const data = ref(initVal)
    const error = ref(null)
    const execute = function () {
        pending.value = true
        error.value = null
        return asyncFn()
            .then((res) => {
                data.value = res as UnwrapRef<T>
                pending.value = false

            }).catch((err) => {
                error.value = err
                pending.value = false
            })
    }
    // 开启立即执行
    if (immediate) {
        execute()
    }

    return {
        // 是否在请求中
        pending,
        // 请求返回的数据
        data,
        // 请求错误信息
        error,
        // 执行函数的区别
        execute,
    }
}